<template>

    <div>

        <h2>商品列表</h2>

        <div class="container">
            <div>
                <el-form :inline="true" :model="params" class="demo-form-inline">
                    <el-form-item>
                        <el-button type="primary" @click="addGoods" size="mini">添加商品</el-button>
                    </el-form-item>
                    <el-form-item label="搜索字段">
                        <el-select v-model="params.field_type" placeholder="搜索字段" size="mini">
                            <el-option label="商品ID" value="goods_id"></el-option>
                            <el-option label="商品名称" value="goods_name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关键词">
                        <el-input v-model="params.keyword" placeholder="关键词" size="mini"></el-input>
                    </el-form-item>
                    <el-form-item label="选项">
                        <el-select v-model="params.goods_type" placeholder="选项" size="mini">
                            <el-option label="全部" value="all"></el-option>
                            <el-option label="热门" value="hot"></el-option>
                            <el-option label="推荐" value="selected"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="reload" size="mini">查询</el-button>
                    </el-form-item>
                </el-form>

            </div>
            <el-table
                    :data="items"
                    style="width: 100%"
                    v-loading="loading">
                <el-table-column
                        prop="id"
                        label="ID"
                >
                </el-table-column>
                <el-table-column
                        prop="class_name"
                        label="大类"
                        >
                </el-table-column>
                <el-table-column
                        prop="type_name"
                        label="子类"
                        >
                </el-table-column>
                <el-table-column
                        prop="goods_name"
                        label="商品名称"
                        >
                </el-table-column>
                <el-table-column
                        prop="sell_price"
                        label="售价"
                        >
                </el-table-column>
                <el-table-column
                        prop="original_price"
                        label="原价"
                        >
                </el-table-column>
                <el-table-column
                        prop="sales_volume"
                        label="销量"
                        >
                </el-table-column>
                <el-table-column label="选项" width="150">
                    <template slot-scope="scope">
                    <el-tag v-if="scope.row.hot==1" size="mini">热门</el-tag>
                    <el-tag v-if="scope.row.selected==1" size="mini">推荐</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="150">
                    <template slot-scope="scope">
                    <el-tag v-if="scope.row.is_onsale==1" size="mini">在售</el-tag>
                    <el-tag v-if="scope.row.is_onsale==0" size="mini">已下架</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作" fixed="right" width="150"
                >
                    <template slot-scope="scope">
                        <el-button @click="editGoods(scope.row)" size="mini">编辑</el-button>
                        <el-button @click="deleteGoods(scope.row)" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                    ref="mainPage"
                    background
                    class="pagination"
                    layout="prev, pager, next"
                    :total="total"
                    :page-size="params.limit"
                    @current-change="setPage"
                    @prev-click="setPage"
                    @next-click="setPage"
            >
            </el-pagination>

        </div>
        <el-dialog  title="商品详情" v-if="goods" :visible.sync="dialogGoodsVisible">
            <div>
                <el-form ref="form" :model="goods" label-width="80px">
                  <el-form-item label="商品名称">
                    <el-input v-model="goods.goods_name" size="small" style="width:300px"></el-input>
                  </el-form-item>
                  <el-form-item label="大类">
                      <el-select v-model="goods.class_id" placeholder="请选择大类" @change="fetchTwoClass" size="small">
                        <el-option v-for="item in classlist" :key="item.id" :label="item.class_name" :value="item.id"></el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item label="子类">
                    <el-select v-model="goods.type_id" placeholder="请选择子类" size="small" :loading="loadChild">
                      <el-option v-for="item in typelist" :key="item.id" :label="item.class_name" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="售价">
                    <el-input v-model="goods.sell_price" size="small" style="width:250px;">
                    <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="市场价">
                    <el-input v-model="goods.original_price" size="small" style="width:250px;">
                    <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="库存">
                    <el-input v-model="goods.store_num" size="small" style="width:120px;"></el-input>
                  </el-form-item>
                  <el-form-item label="热门">
                    <el-radio v-model="goods.hot" :label="0">普通</el-radio>
                    <el-radio v-model="goods.hot" :label="1">热门</el-radio>
                  </el-form-item>
                  <el-form-item label="推荐">
                    <el-radio v-model="goods.selected" :label="0">普通</el-radio>
                    <el-radio v-model="goods.selected" :label="1">推荐</el-radio>
                  </el-form-item>
                  <el-form-item label="推荐">
                      <el-radio v-model="goods.is_onsale" :label="0">下架</el-radio>
                      <el-radio v-model="goods.is_onsale" :label="1">在售</el-radio>
                  </el-form-item>
                    <el-form-item label="规格" :data="goodsSku">
                        <el-button @click="addSku">添加规格</el-button>
                        <el-table :data="goodsSku">
                            <el-table-column prop="sku_name" label="规格名称">
                                <template slot-scope="scope">
                                    <el-input placeholder="规格名称"  v-model="goodsSku[scope.$index].sku_name" style="width: 200px;"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="sku_price" label="规格价格">
                                <template slot-scope="scope">
                                    <el-input placeholder="规格价格" v-model="goodsSku[scope.$index].sku_price" style="width: 200px;"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="#" label="操作">
                                <template slot-scope="scope">
                                    <el-button type="danger" icon="el-icon-delete" @click="deleteSku(goodsSku[scope.$index])"  circle></el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                    <el-form-item label="封面图">
                        <el-upload
                            action="/upload"
                            list-type="picture-card"
                            name="filedata"
                            :file-list="headerfile"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleHeaderRemove"
                            :on-success="handleHeaderSuccess"
                        >
                        </el-upload>
                    </el-form-item>

                  <el-form-item label="缩略图">
                      <el-upload
                        action="/upload"
                        list-type="picture-card"
                        name="filedata"
                        :file-list="filelist_a"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        >
                        <i class="el-icon-plus"></i>
                      </el-upload>
                  </el-form-item>
                  <el-form-item label="详情图">
                    <el-upload
                      action="/upload"
                      list-type="picture-card"
                      name="filedata"
                      :file-list="filelist_b"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleDetailRemove"
                      :on-success="handleDetailSuccess"
                      >
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="doSubmit">保存数据</el-button>
                    <el-button @click="doCancel">取消</el-button>
                  </el-form-item>
              </el-form>
            </div>
        </el-dialog>
    </div>

</template>
<script>
    export default {
        data() {
            return {
              items: [],
              loading: true,
              goods:null,
              dialogGoodsVisible:false,
              classlist:[],
              typelist:[],
              loadChild:false,
              dialogImageUrl: '',
              dialogVisible: false,
              //imagelist:[],
              //detaillist:[],
              filelist_a:[],
              filelist_b:[],
              headerfile:[],
              params: {
                type: 1,
                limit: 10,
                offset: 0,
                field_type: 'goods_name',
                goods_type:'all',
                keyword: '',
                datetime: []
              },
              currentPage: 1,
              total: 0,
              goodsSku:[],
            }
      },
      created() {
        this.fetch();
        this.fetchOneClass();
      },
      methods: {
        fetch() {
          axios.get('/admin/api/goods/search', {params: this.params}).then((res) => {
            if (res.data.code === 0) {
              this.items = res.data.data.items;
              this.total = res.data.data.total;
            } else {
              this.$message(res.data.msg);
            }
            this.loading = false;
          }).catch(function() {
            this.$message('系统错误');
            this.loading = false;
          })
        },

        fetchOneClass(){
          axios.get('/admin/api/goods/childclass/search').then(res=>{
              this.classlist = res.data.data;
          });
        },

        fetchTwoClass(val){
           this.loadChild = true;
           return axios.get('/admin/api/goods/childclass/search',{params:{pid:val}}).then(res=>{
               this.typelist = res.data.data;
               this.loadChild = false;
           });
        },

        handlePictureCardPreview(file) {
          console.log(file)
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;

        },


        handleSuccess(res,file,filelist){
          console.log(res)
          if(res.code==0){
            this.filelist_a.push({id:res.data.id,name:res.data.id,url:res.data.file_url});
          }
        },

          handleHeaderSuccess(res,file,filelist){
              console.log(res)
              if(res.code==0){
                  this.headerfile.push({id:res.data.id,name:res.data.id,url:res.data.file_url});
              }
          },

          handleHeaderRemove(file, fileList) {
              console.log('remove',this.filelist_a,file)
              for(var i=0;i<this.headerfile.length;i++){
                  if(this.headerfile[i].id==file.id){
                      this.headerfile.splice(i,1)
                  }
              }
          },

        handleRemove(file, fileList) {
          console.log('remove',this.filelist_a,file)
          for(var i=0;i<this.filelist_a.length;i++){
              if(this.filelist_a[i].id==file.id){
                this.filelist_a.splice(i,1)
              }
          }
        },

        handleDetailSuccess(res,file,filelist){
          console.log(res)
          if(res.code==0){
            this.filelist_b.push({id:res.data.id,name:res.data.id,url:res.data.file_url});
          }
        },

        handleDetailRemove(file, fileList) {
          console.log(file)
          for(var i=0;i<this.filelist_b.length;i++){
            if(this.filelist_b[i].id==file.id){
              this.filelist_b.splice(i,1)
            }
          }
        },

        addGoods:function() {
            this.dialogGoodsVisible = true;
            this.goods = {};
        },

        doCancel(){
            this.dialogGoodsVisible = false;
            this.goods = {};
        },

        doSubmit(){
            if(this.goods.id && this.goods.id>0){
                this.doUpdate();
            }else{
                this.doAdd();
            }
        },
        addSku:function(){
            this.goodsSku.push({})
        },
        deleteSku(index){
            axios.post('/admin/api/goods/sku/delete',{id:index.id}).then(res=>{
                this.goodsSku.splice(index,1)
            });
        },

        doUpdate(){
            this.goods.image = [];
            this.goods.detail = [];
            this.goods.header = [];
            this.goods.sku = this.goodsSku;
            for(var i=0;i<this.filelist_a.length;i++){
              this.goods.image.push(this.filelist_a[i].id);
            }
            for(var i=0;i<this.filelist_b.length;i++){
              this.goods.detail.push(this.filelist_b[i].id);
            }
            for (var i=0;i<this.headerfile.length;i++){
                this.goods.header.push(this.headerfile[i].id)
            }
            console.log(this.goods)
            this.goods.sku_name = this.goods.sku.sku_name;
            this.goods.sku_price = this.goods.sku.sku_price;
            axios.post('/admin/api/goods/update',this.goods).then(res=>{
              if(res.data.code==0){
                  this.dialogGoodsVisible = false;
                  this.goods = null;
                  this.fetch();
                  this.$message({
                      type: 'success',
                      message: '修改成功!'
                  });
              }
            })
        },

        doAdd(){
            this.goods.image = [];
            this.goods.detail = [];
            this.goods.header = [];
            this.goods.sku = this.goodsSku;
            for(var i=0;i<this.filelist_a.length;i++){
              this.goods.image.push(this.filelist_a[i].id);
            }
            for(var i=0;i<this.filelist_b.length;i++){
              this.goods.detail.push(this.filelist_b[i].id);
            }
            for (var i=0;i<this.headerfile.length;i++){
                this.goods.header.push(this.headerfile[i].id)
            }
            console.log(this.goods)
            axios.post('/admin/api/goods/add',this.goods).then(res=>{
              if(res.data.code==0){
                  this.dialogGoodsVisible = false;
                  this.goods = null;
                  this.fetch();
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
              }
            })

        },

        // 切换分页
        setPage: function(page) {
          this.currentPage = page;
          this.params.offset = (page - 1) * this.params.limit;
          this.fetch()
        },
        // 重新请求接口获取数据，参数发生了变化，页码重置为1
        reload: function() {
          if (this.currentPage === 1) {
            this.fetch();
          } else {
            this.setPage(1);
          }
        },
        editGoods(goods) {
            this.goods = goods;
            this.fetchTwoClass(goods.class_id).then(()=>{
                this.goodsSku = goods.sku;
                console.log(this.goodsSku)
                this.dialogGoodsVisible = true;

                this.filelist_a = [];
                for(var i=0;i<goods.imagelist.length;i++){
                    this.filelist_a.push({id:goods.imagelist[i].id,name:goods.imagelist[i].file_key,url:goods.imagelist[i].file_url});
                }

                this.filelist_b = [];
                for(var i=0;i<goods.detaillist.length;i++){
                    this.filelist_b.push({id:goods.detaillist[i].id,name:goods.detaillist[i].file_key,url:goods.detaillist[i].file_url});
                }
                this.headerfile.push({id:goods.headerimage.id,name:goods.headerimage.file_key,url:goods.headerimage.file_url})

            })
        },
        deleteGoods(goods){
            this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              axios.post('/admin/api/goods/delete',{id:goods.id}).then(res=>{
                this.fetch();
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });
        }
      }
    }
</script>